<!-- GoodsList 商品列表 -->
<template>
  <div class="content">
    <el-form :model="query" ref="searchForm" label-width="100px" size="medium" class="search-form">
      <el-form-item label="创建时间：" prop="timeRange">
        <TimeRangePicker v-model="query.timeRange" type="datetimerange" :defaultTime="['00:00:00', nowHMS]"
                         startPlaceholder="开始时间" endPlaceholder="结束时间"></TimeRangePicker>
      </el-form-item>
      <el-form-item label="商品名称：" prop="keyword">
        <el-input v-model="query.keyword" placeholder="请输入商品名称" @keyup.enter.native="handleSearch"></el-input>
      </el-form-item>
      <el-form-item label="品牌名称：" prop="brandName">
        <BrandName placeholder="请输入品牌名称" @getBrandName="getBrandName"></BrandName>
      </el-form-item>

      <el-form-item label="价格：" prop="priceRange">
        <InputNumber v-model="query.priceRange"></InputNumber>
      </el-form-item>

      <!-- <el-form-item label="访客量：" prop="priceRange">
        <InputNumber v-model="query.priceRange"></InputNumber>
      </el-form-item>

      <el-form-item label="浏览量：" prop="priceRange">
        <InputNumber v-model="query.priceRange"></InputNumber>
      </el-form-item> -->

      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader clearable v-model="query.productCategoryId" :props="{ value: 'id', label: 'name', checkStrictly: true }"
                     :options="classList" placeholder="请选择商品分类"></el-cascader>
      </el-form-item>
      <el-form-item label-width="0px">
        <Cbutton @click="handleSearch" size="medium">查询</Cbutton>
        <Cbutton type="info" size="medium" @click="handleReset('searchForm')">重置</Cbutton>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <div class="content-btn">
        <Cbutton @click="handleAdd">添加商品</Cbutton>
      </div>
      <el-tab-pane label="上架中" name="1"></el-tab-pane>
      <el-tab-pane label="仓库中" name="2"></el-tab-pane>
      <el-tab-pane label="已售罄" name="3"></el-tab-pane>
      <el-tab-pane label="全部" name="4"></el-tab-pane>
       <!-- <el-tab-pane label="审核" name="4"></el-tab-pane> -->
    </el-tabs>

    <div class="content-container">
      <el-table :data="tableList" v-loading="tableLoading" ref="tableData" border fit @sort-change="sortTableData">
        <el-table-column label="序号" type="index" align="center" width="70"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center" min-width="200">
          <template slot-scope="scope">
            <div class="product">
              <div class="product-img">
                <el-image class="product-img-small" :src="scope.row.albumPicture" :preview-src-list="[scope.row.albumPicture]"></el-image>
              </div>
              <div class="product-word">
                <span class="click-ele" @click="handleEdit(scope.row, 'name', '商品名称')">{{scope.row.name}}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="detailTitle" label="商品别名" align="center" min-width="180">
          <template slot-scope="scope">
            <el-popover v-if="scope.row.detailTitle && scope.row.detailTitle.length > 20" placement="top-start" title=""
                        width="240" trigger="hover" :content="scope.row.detailTitle">
              <span slot="reference">{{scope.row.detailTitle.substring(20, 0) + '...'}}</span>
            </el-popover>
            <div v-else>{{ scope.row.detailTitle }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" align="center" min-width="130"></el-table-column>
        <el-table-column prop="shopName" label="商铺" align="center" min-width="110"></el-table-column>
        <el-table-column prop="productCategoryName" label="分类名称" align="center"></el-table-column>
        <el-table-column prop="productStyle" label="商品规格" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.productStyle === 1 ? '单':'多'}}规格</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格" sortable align="center" min-width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.productStyle === 1" class="click-ele" @click="handleEdit(scope.row, 'price', '商品价格')">
              {{scope.row.price ? Number(scope.row.price).toFixed(2) : '0.00'}}
            </span>
            <span v-else class="click-ele" @click="handleEdit(scope.row, 'price', '商品价格')">{{scope.row.originPrice}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="usePointLimit" label="积分价格" sortable align="center" min-width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.productStyle === 1" class="click-ele" @click="handleEdit(scope.row, 'usePointLimit', '积分价格')">{{scope.row.usePointLimit
              || 0}}</span>
            <span v-else class="click-ele" @click="handleEdit(scope.row, 'usePointLimit', '积分价格')">{{scope.row.originUsePointLimit}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" sortable align="center">
          <template slot-scope="scope">
            <span class="click-ele" @click="handleEdit(scope.row, 'stock', '库存')">{{scope.row.stock}}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="recommandStatus" label="推荐商品" sortable align="center" min-width="130">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.recommandStatusSwitch" @change="handleSetRecommandStatus(scope.row)"></el-switch>
          </template>
        </el-table-column> -->
        <el-table-column prop="uv_count" label="访问量" align="center" min-width="130">
          <template slot-scope="scope">
            <p>访客量：{{scope.row.uv_count}}</p>
            <p>浏览量：{{scope.row.pv_count}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="sale" label="销售量" sortable align="center" min-width="130"></el-table-column>
        <el-table-column prop="virtualSale" label="虚拟销量" align="center">
          <template slot-scope="scope">
            <span class="click-ele" @click="handleEdit(scope.row, 'virtualSale', '虚拟销量')">{{scope.row.virtualSale ||
              0}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="replayCount" label="评价" align="center" min-width="140">
          <template slot-scope="scope">
            <span class="click-ele" @click="handleEdit(scope.row, 1)">评价数：{{scope.row.replayCount || 0}}</span> <br />
            <span class="click-ele" @click="handleEdit(scope.row, 1)">好评率：{{scope.row.replayRate ? scope.row.replayRate
              * 100 + '%'
              : '0.00' + '%'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" sortable align="center">
          <template slot-scope="scope">
            <span class="click-ele" @click="handleEdit(scope.row, 'sort', '排序')">{{scope.row.sort}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
          <template slot-scope="scope">
            {{scope.row.createTime | glbTimeFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="140" align="center">
          <template slot-scope="scope">
            <!-- 上架状态：0->仓库中；1->上架；2->下架 -> 3已售罄 -->
            <span class="click-ele" @click="handleEdit(scope.row, 2)">编辑</span>
            <span v-if="scope.row.publishStatus === 1" class="click-ele danger" @click="handleUpLow(scope.row)">下架</span>
            <span v-if="scope.row.publishStatus === 0" class="click-ele success" @click="handleUpLow(scope.row)">上架</span>
            <span class="click-ele danger" @click="handleRemove(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>

      <Pagination @pageChange="getPage" :pageDefultData="{
        pageNum: query.pageNum,
        pageRow: query.pageSize,
        totalCount: totalCount }">
      </Pagination>
    </div>
  </div>
</template>

<script>
import TimeRangePicker from '@/components/DatePicker/TimeRangePicker'
import BrandName from '@/components/Brand'
import InputNumber from '@/components/InputNumber'
import { ExportList, NowDateTime } from '@/utils'
import { GetProductList, ProductUpLowFrames, ProductRemove, EditQuickProduct, GetProductClassifyList } from '@/api/onlineMan'
import { mapGetters } from 'vuex'
export default {
  name: 'GoodsList',
  components: { TimeRangePicker, BrandName, InputNumber },
  data () {
    return {
      activeName: '1',
      nowHMS: NowDateTime(),
      query: {
        timeRange: [],
        keyword: '',
        productCategoryId: '',
        brandName: '',
        column: '',
        order: '',
        priceRange: [],
        minPrice: '',
        maxPrice: '',
        orderBy: '',
        sort: '',
        pageNum: 1,
        pageSize: 10
      },
      totalCount: 0,
      tableList: [],
      tableSelectList: [],
      tableLoading: false,
      goodsClassList: ExportList('goodsClassList'),
      classList: []
    }
  },
  props: {},
  watch: {},
  computed: {
    ...mapGetters([
      'routerParams'
    ])
  },
  created () {
    if (this.routerParams['$pageName'] === this.$route.name) {
      this.activeName = this.routerParams.activeName
      this.query.status = this.activeName
      this.query.pageNum = this.routerParams.pageNum
      this.query.pageSize = this.routerParams.pageSize
    }
  },
  mounted () {
    this.getClass()
    this.getList()
  },
  methods: {
    getBrandName (val) {
      this.query.brandName = val
    },
    getList () {
      let params = {}
      if (this.query.timeRange && this.query.timeRange.length > 1) {
        params.createTimeSt = this.query.timeRange[0]
        params.createTimeEn = this.query.timeRange[1]
      }
      if (this.query.priceRange && this.query.priceRange.length > 1) {
        params.minPrice = this.query.priceRange[0]
        params.maxPrice = this.query.priceRange[1]
      }
      if (this.query.keyword) params.keyword = this.query.keyword
      params.pageNum = this.query.pageNum
      params.pageSize = this.query.pageSize
      params.brandName = this.query.brandName
      params.orderBy = this.query.orderBy
      params.sort = this.query.sort
      params.productCategoryId = this.query.productCategoryId[this.query.productCategoryId.length - 1]
      this.tableLoading = true

      GetProductList(params, this.activeName).then(res => {
        this.tableLoading = false
        const data = res.data
        let tableList = res.data.list
        tableList.forEach(item => {
          item.recommandStatusSwitch = item.recommandStatus === 1
          if (item.pic) {
            item.albumPicture = item.pic
          } else if (!item.pic && item.albumPics) {
            item.albumPictures = item.albumPics.split(',')
            item.albumPicture = item.albumPics.split(',')[0]
          } else {
            item.albumPicture = ''
          }
        })
        this.tableList = data.list
        this.totalCount = data.total
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleAdd () {
      this.$router.push({ name: 'pms:goods:add' })
    },
    handleTabClick (val) {
      this.query.pageNum = 1
      this.getList()
    },
    handleSearch () {
      this.handleClearSort()
      this.query.pageNum = 1
      this.getList()
    },
    handleReset (formName) {
      this.$refs[formName].resetFields()
    },
    handleSetRecommandStatus (row) {
      const params = {
        id: row.id,
        recommandStatus: row.recommandStatus === 1 ? '0' : '1'
      }
      EditQuickProduct(params).then(res => {
        this.getList()
      })
    },
    handleEdit (row, type, tips = '') {
      if (type === 1) {
        // 跳转 商品评价
        this.$store.dispatch('setPageRouterParams', {
          $pageName: this.$route.name,
          activeName: this.activeName,
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize,
          pageRow: this.query.pageSize
        })
        this.$router.push({ name: 'pms:goods:evaluate', query: { id: row.id, name: row.name } })
      } else if (type === 2) {
        // 跳转 商品编辑
        this.$store.dispatch('setPageRouterParams', {
          $pageName: this.$route.name,
          activeName: this.activeName,
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize
        })
        this.$router.push({ name: 'pms:goods:edit', query: { id: row.id } })
      } else {
        let params = {
          id: row.id
        }
        // /^([1-9]\d{1,9}|\d)(\.\d{1,2})?$/ 非负数字
        // /^([1-9]\d*|[0]{1,1})$/ 含零的正整数

        // 多规格商品 不可单独更改 价格 库存
        if (row.productStyle === 2) {
          if (type === 'price' || type === 'stock' || type === 'usePointLimit') {
            this.$message.warning('多规格商品 不可单独更改 价格 库存')
            return
          }
        }

        let inputPatternReg = /^([1-9]\d*|[0]{1,1})$/
        let inputErrorMessage = '格式不正确'
        if (type === 'price') {
          inputPatternReg = /^([1-9]\d{1,9}|\d)(\.\d{1,3})?$/
          inputErrorMessage = '价格不正确（整数、不超过3位小数的数字）'
        }
        if (type === 'name') {
          inputPatternReg = /^.{1,31}$/
          inputErrorMessage = '商品名称不超过30字'
        }
        this.$prompt('', '修改' + tips, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: row[type] ? row[type].toString() : '0',
          inputPattern: inputPatternReg,
          inputErrorMessage: inputErrorMessage
        }).then(({ value }) => {
          params[type] = value
          EditQuickProduct(params).then(res => {
            this.getList()
          }).catch(() => { })
        }).catch(() => { })
      }
    },

    handleUpLow (row) {
      let parmas = { id: row.id }
      let Tips = '上架'
      if (row.publishStatus === 1) {
        // 下架
        parmas.publishStatus = '0'
        Tips = '下架'
      }
      if (row.publishStatus === 0) {
        // 上架
        parmas.publishStatus = '1'
        Tips = '上架'
      }
      this.$confirm(`确定要${Tips}该商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ProductUpLowFrames(parmas).then(res => {
          this.$message.success(res.message || Tips + '成功')
          this.getList()
        }).catch(() => { })
      }).catch(() => { })
    },
    handleRemove (row) {
      let parmas = {
        id: row.id
      }
      this.$confirm(`确定要删除该商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ProductRemove(parmas).then(res => {
          // this.$message.success(res.message || '删除成功')
          this.getList()
        }).catch(() => { })
      }).catch(() => { })
    },
    sortTableData ({ column, prop, order }) {
      // column 列属性 prop 排序字段 order[descending, ascending] 升降序
      this.query.orderBy = prop
      if (order) {
        this.query.sort = order.indexOf('asc') > -1 ? 'asc' : 'desc'
      } else {
        this.query.sort = ''
      }
      this.query.page = 1
      this.getList()
    },
    // 清除排序
    handleClearSort () {
      this.$refs.tableData.clearSort()
      this.query.orderBy = ''
      this.query.sort = ''
    },
    getPage (val) {
      this.query.pageNum = val.pageNum
      this.query.pageSize = val.pageRow
      this.getList()
    },
    getClass () {
      const params = {
        pageNum: 1,
        pageSize: 30
      }
      GetProductClassifyList(params).then(res => {
        res.data.map(item => {
          if (item.children && item.children.length === 0) {
            delete item.children
          }
          if (item.children && item.children.length >= 1) {
            item.children.map(items => {
              if (items.children && items.children.length === 0) {
                delete items.children
              }
            })
          }
        })
        this.classList = res.data
      }).catch(() => { })
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
